const { generateToken } = require('../utils/token');
const { success, badRequest, unauthorized, conflict, error } = require('../utils/response');
const userModel = require('../models/userModel');

const register = async (req, res) => {
  try {
    const { username, email, password } = req.body;
    
    if (!username || !email || !password) {
      return badRequest(res, 'Please provide all required fields');
    }
    
    const existingUser = await userModel.findUserByEmail(email);
    if (existingUser) {
      return conflict(res, 'Email already exists');
    }
    
    const userId = await userModel.createUser(username, email, password);
    const user = await userModel.findUserById(userId);
    const token = generateToken(userId);
    
    success(res, { user, token }, 'User registered successfully');
  } catch (err) {
    error(res, err.message);
  }
};

const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    
    if (!email || !password) {
      return badRequest(res, 'Please provide email and password');
    }
    
    const user = await userModel.findUserByEmail(email);
    if (!user) {
      return unauthorized(res, 'Invalid credentials');
    }
    
    const isMatch = await userModel.comparePassword(password, user.password);
    if (!isMatch) {
      return unauthorized(res, 'Invalid credentials');
    }
    
    const token = generateToken(user.id);
    const userData = await userModel.findUserById(user.id);
    
    success(res, { user: userData, token }, 'Login successful');
  } catch (err) {
    error(res, err.message);
  }
};

const getProfile = async (req, res) => {
  try {
    const user = await userModel.findUserById(req.userId);
    if (!user) {
      return notFound(res, 'User not found');
    }
    success(res, user);
  } catch (err) {
    error(res, err.message);
  }
};

const updateProfile = async (req, res) => {
  try {
    const { username, email } = req.body;
    await userModel.updateUserProfile(req.userId, username, email);
    const user = await userModel.findUserById(req.userId);
    success(res, user, 'Profile updated successfully');
  } catch (err) {
    error(res, err.message);
  }
};

const updateAvatar = async (req, res) => {
  try {
    if (!req.file) {
      return badRequest(res, 'No file uploaded');
    }
    
    const avatarPath = `/uploads/${req.file.filename}`;
    await userModel.updateUserAvatar(req.userId, avatarPath);
    const user = await userModel.findUserById(req.userId);
    success(res, user, 'Avatar updated successfully');
  } catch (err) {
    error(res, err.message);
  }
};

module.exports = {
  register,
  login,
  getProfile,
  updateProfile,
  updateAvatar
};